//
//  MailGoodsContentCell.m
//  WoWeiRenRenOC
//
//  Created by 姜孟东 on 2020/6/12.
//  Copyright © 2020 姜孟东. All rights reserved.
//

#import "MailGoodsContentCell.h"
#import "NSString+js.h"
@interface MailGoodsContentCell ()<UIScrollViewDelegate,WKNavigationDelegate>
@property (assign, nonatomic)CGFloat Wnheight;
@end
@implementation MailGoodsContentCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    
    self.webView.navigationDelegate = self;

    self.webView.scrollView.scrollEnabled = NO;
    self.webView.backgroundColor = [UIColor clearColor];
    self.webView.userInteractionEnabled = NO;
    

}

- (WKWebView *)webView {
    
    if (!_webView) {
       
        WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
        NSString *jSString = [NSString stringWithFormat:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=%f'); document.getElementsByTagName('head')[0].appendChild(meta);",kScreenW-30];
        WKUserScript *wkUserScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        [wkWebConfig.userContentController addUserScript:wkUserScript];
        
         _webView = [[WKWebView alloc]initWithFrame:CGRectMake(15, 50, KSCREEN_WIDTH - 30, 100) configuration:wkWebConfig];
        
        [self.contentView addSubview:_webView];
    }
    return _webView;
    
}


- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {

    return nil;

}




- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state    
}

- (void)setModel:(MailGoodsDetailsModel *)model {
    
    _model  = model;
    if ([CommonTTool isStrNull:model.introduction]) {
        return;
    }
    
    NSString * text = self.model.introduction;

    if (![CommonTTool validateHttpwithString:text]) {
        [self.webView loadHTMLString:text baseURL:nil];
    }else {
        NSString *htmlString = [NSString stringWithFormat:@"<html> \n"
        "<head> \n"
        "<style type=\"text/css\"> \n"
        "body {font-size:15px;}\n"
        "</style> \n"
        "</head> \n"
        "<body>"
        "<script type='text/javascript'>"
        "window.onload = function(){\n"
        "var $img = document.getElementsByTagName('img');\n"
        "for(var p in  $img){\n"
        " $img[p].style.width = '100%%';\n"
        "$img[p].style.height ='auto'\n"
        "}\n"
        "}"
        "</script>%@"
        "</body>"
        "</html>", model.introduction];
        [self.webView loadHTMLString:htmlString baseURL:nil];
    }
    
//    [_webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];

    
}



- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
//    [[NSNotificationCenter defaultCenter]postNotificationName:@"getCellHightNotification" object:nil userInfo:@{@"height":[NSNumber numberWithFloat:self.Wnheight]}];
    [webView evaluateJavaScript:@"document.body.offsetHeight" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
           // 计算webView高度
        CGFloat height = [result doubleValue];
        if (height < 50) {
            return;
        }
        self.webView.frame = CGRectMake(15, 50, KSCREEN_WIDTH - 30, height + 10);
        height += 70;
        self.Wnheight = height;
        [[NSNotificationCenter defaultCenter]postNotificationName:@"getCellHightNotification" object:nil userInfo:@{@"height":[NSNumber numberWithFloat:self.Wnheight]}];
        
       }];
//    CGSize fitSize = _webView.scrollView.contentSize;
    //        NSLog(@"webview fitSize:%@",NSStringFromCGSize(fitSize));
            
//            CGFloat height = fitSize.height;
//            if (height < 50) {
//                return;
//            }
//            self.webView.frame = CGRectMake(15, 50, KSCREEN_WIDTH - 30, fitSize.height);
//            height += 50;
//            self.Wnheight = height;
//    [[NSNotificationCenter defaultCenter]postNotificationName:@"getCellHightNotification" object:nil userInfo:@{@"height":[NSNumber numberWithFloat:self.Wnheight]}];
//    NSString * text = self.model.introduction;
    NSString * text = self.model.introduction;
    if ([CommonTTool validateHttpwithString:text]) {
//        NSString *bodyStyle = @"document.getElementsByTagName('body')[0].style.textAlign = 'center';";
//
//        [webView evaluateJavaScript:bodyStyle completionHandler:nil];
//
//        NSString *bodyStyle1 = @"document.getElementsByTagName('body')[0].style.width = '100px';";
//        [webView evaluateJavaScript:bodyStyle1 completionHandler:nil];
//        NSString *meta = [NSString stringWithFormat:@"document.getElementsByName(\"viewport\")[0].content = \"width=%f, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"", 10];
        
//        [webView evaluateJavaScript:meta completionHandler:nil];

        
    }else {
        // 网页加载完成后，，设置字体大小
        [webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '100%'" completionHandler:nil];

        //字体颜色
        [webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= '#2A2A2A'" completionHandler:nil];
        // 文字居中显示
        NSString *bodyStyle = @"document.getElementsByTagName('body')[0].style.textAlign = 'left';";
        [webView evaluateJavaScript:bodyStyle completionHandler:nil];
    }

       
   


}


-(void)layoutSubviews
{
    [super layoutSubviews];
}

//监听方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"contentSize"]) {

//        CGSize fitSize = [_webView sizeThatFits:CGSizeZero];
        CGSize fitSize = _webView.scrollView.contentSize;
//        NSLog(@"webview fitSize:%@",NSStringFromCGSize(fitSize));
        
        CGFloat height = fitSize.height;
        if (height < 50) {
            return;
        }
        self.webView.frame = CGRectMake(15, 50, KSCREEN_WIDTH - 30, fitSize.height);
        height += 50;
        self.Wnheight = height;
        
    }
}

//这里别忘了在dealloc理移除监听
- (void)dealloc {
//    if (![CommonTTool isStrNull:self.model.introduction]) {
//        [self.webView.scrollView removeObserver:self
//                                        forKeyPath:@"contentSize" context:nil];
//    }
   
}

@end
